package com.tjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tjl.model.Commodity;

import com.tjl.service.Impl.CommodityServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author TJL
 * @date 2022/5/25
 */
@RestController
@RequestMapping("/commoditys")
public class CommodityController {
    @Autowired
    private CommodityServiceImpl commodityService;

    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping("/search")
    public CodeMsg search(String name){
        QueryWrapper<Commodity> qw = new QueryWrapper<>();
        qw.like("name",name);
        return new CodeMsg(commodityService.list(qw));
    }

    @GetMapping
    public CodeMsg getCommodityService(Integer typeid,String name,Integer state,String hot) {

        QueryWrapper<Commodity> objectQueryWrapper = new QueryWrapper();

        /**
         * 分类
         */
        if (typeid != null){
            objectQueryWrapper.eq("typeid",typeid);
        }

        /**
         * 是否热门
         */
        if (hot != null){
            objectQueryWrapper.eq("hot",hot);
        }

        /**
         * 商品状态
         */
        if (state != null){
            objectQueryWrapper.eq("state",state);
        }

        /**
         * 搜索名字
         */
        if (Strings.isNotEmpty(name)){
            objectQueryWrapper.like("name",name);
        }
        return new CodeMsg(commodityService.list(objectQueryWrapper));
    }

    @GetMapping("/{id}")
    public CodeMsg getOne(@PathVariable Integer  id){

        return new CodeMsg(commodityService.getOneById(id));
    }



    @PostMapping
    public CodeMsg add(@RequestBody Commodity commodity,@RequestHeader String token) {
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(commodityService.save(commodity));
    }

    @PutMapping
    public CodeMsg put(@RequestBody Commodity commodity,@RequestHeader String token){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(commodityService.updateById(commodity));
    }

    @DeleteMapping("/{id}")
    public CodeMsg delete(@PathVariable Integer id,@RequestHeader String token) {
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(commodityService.removeById(id));
    }

}
